/*
 *Author: 蔡亚风
 *Date: 2022-06-22 16:21:33
 *LastEditTime: 2022-06-29 16:25:44
 *LastEditors: 蔡亚风
 *Description:
 *FilePath: \prod\src\utils\directive.js
 */
import BigInput from '../components/BigInput/register'
import { nextTick } from 'vue'

const sharpEnter = {
  flag: false, //用于二次调用focus处理防抖开关
  async mounted(el, { value }) {
    //等待实例dom加载完成
    await nextTick()
    //获取输入框dom
    const inputDom = ['INPUT', 'TEXTAREA'].includes(el.nodeName)
      ? el
      : el.querySelector('input') || el.querySelector('textarea')
    if (!inputDom) {
      throw new Error('放大输入框：当前绑定DOM中无input或textarea类型')
    }
    //输入等待开关
    let isInputZh = false
    const hackFunction = async () => {
      if (sharpEnter.flag) return false//如果刚结束的focus事件开关为打开则不继续下一步
      if (isInputZh) return false //如果输入框还在输入等待中则不进行过滤
      let res = ''
      try {
        //调用组件传值进去 拿值回来
        res = await BigInput({
          filterInputData: value,
          val: inputDom.value,
          maxlength: inputDom.getAttribute('maxlength'),
        })
      } catch (error) {
        console.log(error)
      } finally {
        //打开开关 防止二次弹起
        sharpEnter.flag = true
        inputDom.value = res
        //因为是通过js直接改变input的值，没有触发vue双向绑定，所以需要手动触发input事件
        inputDom.dispatchEvent(new Event('input'))
        inputDom.dispatchEvent(new Event('change'))
        //在实际流程中发现单纯的input事件无法触发element的输入校验，还需要再次触发focus事件
        inputDom.dispatchEvent(new Event('focus'))
        inputDom.dispatchEvent(new Event('blur'))
        //防抖
        setTimeout(() => {
          sharpEnter.flag = false
        }, 200)
      }
    }
    inputDom.addEventListener(
      'compositionstart',
      (e) => {
        //中文输入等待start
        isInputZh = true
      },
      false
    )
    inputDom.addEventListener(
      'compositionend',
      (e) => {
        //中文输入等待end
        isInputZh = false
        /**
         * @hackFunction
         *  sometime oninput会在compositionend结束前调用 这样的oninput会直接被return
         */
         hackFunction()
      },
      false
    )
    //原始输入框被点击获取焦点后调用封装组件
    inputDom.onfocus = () => {
      hackFunction()
    }
  },
  beforeUnmount(el) {
    //实例销毁操作
    console.log('beforeUnmount')
    const inputDom = ['INPUT', 'TEXTAREA'].includes(el.nodeName)
      ? el
      : el.querySelector('input') || el.querySelector('textarea')
    //解绑
    inputDom.removeEventListener('compositionstart', null, false)
    inputDom.removeEventListener('compositionend', null, false)
    inputDom.onfocus = null
  },
}
export { sharpEnter }
